<?php

namespace common\service;

use common\exception\LogicException;
use common\model\ProjectCapacityReportMonthModel;
use support\EntityTaskFilterParser;
use support\ErrorCode;
use support\SingletonTrait;

class ProjectCapacityReportMonthService
{
    // 单例工具
    use SingletonTrait;

    use EntityTaskFilterParser;


    /**
     * 保存产能上报数据
     * @param $param
     * @return int
     * @throws \Exception
     */
    public function saveProjectCapacityReportMonth($param)
    {
        //判断月份
        $reportTime = strtotime($param['report_moth']);
        if (!$reportTime) {
            throw new LogicException('report_moth data error.', ErrorCode::INCORRECT_DATA_FORMAT);
        }

        $reportMonth = date('Ym', $reportTime);
        //环节ID可能多个
        $stepCategoryIdList = $param['step_category_id_list'];

        $reportMonthModel = model(ProjectCapacityReportMonthModel::class);
        $reportMonthModel->startTrans();

        try {
            foreach ($stepCategoryIdList as $val) {
                $this->insertOrUpdateReportMonthData($param['project_id'], $reportMonth, $val, $param);
            }
            $reportMonthModel->commit();
        } catch (\Throwable $e) {
            $reportMonthModel->rollback();
            trace(format_exception_info($e), 'ERR');
            throw new LogicException('Incorrect data format.', ErrorCode::INCORRECT_DATA_FORMAT);
        }

        return 1;
    }


    /**
     * 新增 或 修改 上报月记录
     * @param int   $projectId      项目ID
     * @param int   $reportMoth     上报月份
     * @param int   $stepCategoryId 环节ID
     * @param array $param          产能
     * @return int
     * @throws \Exception
     */
    private function insertOrUpdateReportMonthData(int $projectId, int $reportMoth, int $stepCategoryId, array $param)
    {
        $reportMonthModel = model(ProjectCapacityReportMonthModel::class);
        $reportMonthInfo = $reportMonthModel
            ->where([
                'project_id' => $projectId,
                'step_category_id' => $stepCategoryId,
                'type' => $param['type'] ?? 1,
                'report_moth' => $reportMoth
            ])
            ->find();

        $data = [];
        $data['number'] = $param['number'];

        if ($reportMonthInfo) {
            $data['id'] = $reportMonthInfo['id'];

            $reportMonthModel->modifyItem($data);
        } else {
            $data['type'] = $param['type'] ?? 1;
            $data['project_id'] = $projectId;
            $data['report_year'] = substr($reportMoth, 0, 4);
            $data['report_moth'] = $reportMoth;
            $data['step_category_id'] = $stepCategoryId;

            $reportMonthModel->addItem($data);
        }
        return 1;
    }


    /**
     * 按年查询--产能月报表
     * @param int $projectId      项目
     * @param int $stepCategoryId 年
     * @param int $reportYear     环节ID
     * @return array
     */
    public function getMonthReportListByYear(int $projectId, int $stepCategoryId, int $reportYear)
    {
        $reportMonthModel = model(ProjectCapacityReportMonthModel::class);
        $reportMonthList = $reportMonthModel
            ->field('id,report_moth, number, type')
            ->where([
                'project_id' => $projectId,
                'step_category_id' => $stepCategoryId,
                'report_year' => $reportYear
            ])
            ->order('report_moth asc')
            ->select();

        //组装数据 -- 内部产能 - 外部产能 - 需求量
        $innerList = $outList = $requireList = $reportList = [];
        foreach ($reportMonthList as &$val) {
            $val['report_moth'] = intval(substr($val['report_moth'], 4));
            $val['member_num'] = 0;

            if ($val['type'] == ProjectCapacityReportMonthModel::TYPE_INER_NUMBER) {
                $innerList[] = $val;
            }
            if ($val['type'] == ProjectCapacityReportMonthModel::TYPE_OUT_NUMBER) {
                $outList[] = $val;
            }
            if ($val['type'] == ProjectCapacityReportMonthModel::TYPE_REQUIREMENT) {
                $requireList[] = $val;
            }
        }
        $reportList['inner_list'] = $innerList;
        $reportList['out_list'] = $outList;
        $reportList['requirement_list'] = $requireList;

        return $reportList;
    }


    /**
     * 获取产能月数据 多个项目IDs
     * @param array      $projectIds     项目ID数组
     * @param int        $stepCategoryId 环节ID
     * @param int|string $reportMoth     年月
     * @return array|int
     */
    public function getMonthReportNumberByMonths(array $projectIds, int $stepCategoryId,  $reportMoth)
    {
        $innerType = ProjectCapacityReportMonthModel::TYPE_INER_NUMBER;
        $outType = ProjectCapacityReportMonthModel::TYPE_OUT_NUMBER;
        $requireType = ProjectCapacityReportMonthModel::TYPE_REQUIREMENT;
        //产能分类 统计
        $field = "SUM( if(type={$innerType}, number, 0)) as  inner_num,
                  SUM( if(type={$outType}, number, 0)) as  out_num,
                  SUM( if(type={$requireType}, number, 0)) as  require_num";
        //月份  eg:2023-03
        if (is_string($reportMoth)) {
            $reportMoth = str_replace('-', '', $reportMoth);
        }
        $reportMonthModel = model(ProjectCapacityReportMonthModel::class);
        $monthNumberList = $reportMonthModel
            ->where([
                'project_id' => ['in', $projectIds],
                'step_category_id' => $stepCategoryId,
                'report_moth' => $reportMoth
            ])->field($field)->find();

        $rt = [];
        $rt['product_capacity'] = $monthNumberList['inner_num'] ?? 0;
        $rt['product_capacity_out'] = $monthNumberList['out_num'] ?? 0;
        $rt['requirement_num'] = $monthNumberList['require_num'] ?? 0;
        return $rt ?? 0;
    }

}
